package cloud.demarcia.crawler3.processors.Impl;

import cloud.demarcia.crawler3.entities.Page;
import cloud.demarcia.crawler3.entities.Selenarctos;
import cloud.demarcia.crawler3.processors.Processor;
import cloud.demarcia.crawler3.repositories.SelenarctosRepository;
import cloud.demarcia.crawler3.utils.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import wen.Downloader;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;


@Service
public class SelenarctosProcessor implements Processor {


    @Value("${init.location}")
    private String fileLocation;


    private final SelenarctosRepository selenarctosRepository;


    public SelenarctosProcessor(SelenarctosRepository selenarctosRepository) {
        this.selenarctosRepository = selenarctosRepository;
    }

    @Override
    public List<Page> process(Document document) throws IOException {
        List<Page> resList = new LinkedList<>();
        assert fileLocation != null;
        Downloader downloader = new Downloader(fileLocation + "/selenarctos/avatars", "-avatars.jpg");

        List<Element> heroElements = document.getElementsByClass("herolist clearfix").get(0).children();

        System.out.println("[CRAWLER] Processing selenarctos page...");
        for (Element heroElement : heroElements) {
            Selenarctos selenarctos = (Selenarctos) element2Object(heroElement);
            selenarctosRepository.save(selenarctos);
            downloader.addATask(selenarctos.getAvatarLink(), selenarctos.getName());
            Page page = new Page(selenarctos.getInfoPageLink(), "selenarctosInfoPage");
            resList.add(page);
        }
        Thread download = new Thread(downloader);
        download.start();
        return resList;
    }

    @Override
    public Object element2Object(Element heroElement) {
        Selenarctos selenarctos = new Selenarctos();
        StringUtils stringUtils = new StringUtils();
        selenarctos.setInfoPageLink("http://pvp.qq.com/web201605/" + heroElement.child(0).attr("href"));
        String picLink = heroElement.child(0).child(0).attr("src");
        selenarctos.setAvatarLink("http:" + picLink);
        selenarctos.setIdOnSite(stringUtils.extractIdFromLink(picLink));
        selenarctos.setName(heroElement.text());
        return selenarctos;
    }
}
